﻿using Microsoft.Extensions.Caching.Memory;
using SocketGateway.Tool;
using TK.TSocket;

namespace SocketGateway
{
    /// <summary>
    /// 数据接收器
    /// </summary>
    public class ReceiveData : IReceiveData
    {
        private readonly IMemoryCache _memoryCache;

        /// <summary>
        /// ctor
        /// </summary>
        public ReceiveData(IMemoryCache memoryCache)
        {
            _memoryCache = memoryCache;
        }

        /// <summary>
        /// 数据接收
        /// </summary>
        public Task ReceiveDataAsync(DataPacket dataPacket)
        {
            CacheLogData(dataPacket);

            return Task.CompletedTask;
        }

        #region private methods
        /// <summary>
        /// 缓存日志数据
        /// </summary>
        private void CacheLogData(DataPacket data)
        {
            if (!string.IsNullOrWhiteSpace(data.ClientId))
            {
                if (_memoryCache.TryGetValue<string>(data.ClientId, out _))
                {
                    var msg = Newtonsoft.Json.JsonConvert.SerializeObject(data);
                    if (Data.LogData.TryGetValue(data.ClientId, out var log))
                    {
                        if (log.Count >= 5)
                            log.RemoveAt(4);
                        log.Insert(0, msg);
                    }
                    else
                        Data.LogData.TryAdd(data.ClientId, new List<string> { msg });
                }
            }
        }
        #endregion
    }
}
